import json

from django.core.paginator import Paginator

from apps.aiauth.models import Users
from utils import restful, md5
from .serializers import AdminUsersSerializer


def AllUserInfo(request):
    pagenow = request.GET.get('pagenow', 1)
    studentId = request.GET.get('studentId')
    if studentId:
        allUsers = Users.objects.filter(studentid=studentId).order_by('user_id')
    else:
        allUsers = Users.objects.all().order_by('user_id')
    page_obj = Paginator(allUsers, 10)
    page_data = page_obj.get_page(pagenow)
    totalcount = page_obj.count
    data = AdminUsersSerializer(page_data.object_list, many=True).data

    return restful.ok(message='成功', data={'data': data, 'totalcount': totalcount})


def updateUserInfo(request):
    requestBody = json.loads(request.body)
    userid = requestBody['user_id']
    user = Users.objects.get(user_id=userid)
    studentid = requestBody['studentid']
    username = requestBody['username']
    phonenumber = requestBody['phonenumber']
    email = requestBody['email']
    user.studentid = studentid
    user.username = username
    user.phonenumber = phonenumber
    user.email = email
    user.save()

    return restful.ok(message='成功')


def resetPassword(request):
    userid = request.GET.get('userid')
    user = Users.objects.get(user_id=userid)
    user.password = md5.md5('123456')
    # user.password = '123456'
    user.save()

    return restful.ok(message='成功')

